package org.osomit.sacct.builder;

import org.osomit.sacct.entity.Response;
import org.osomit.sacct.entity.ApplicationAccount;
import org.osomit.sacct.entity.SessionInfo;

import java.util.Map;
import java.util.List;
import java.util.ArrayList;

/**
 * @author Jian Fang (John.Jian.Fang@gmail.com)
 *
 * Date: Jun 28, 2009
 */
public class ResponseBuilder extends BaseBuilder<Response>{

    public Response build(Object object) {
        if(object != null){
            Response resp = new Response();
            Map map = (Map) object;
            resp.setCommand((String)map.get(Response.COMMAND));
            resp.setSuccessful((Boolean)map.get(Response.IS_SUCCESSFUL));
            resp.setErrorCode((String)map.get(Response.ERROR_CODE));
            List list = (List)map.get(Response.RETURN_VALUE);
            if(list != null && list.size() > 0){
                List params = new ArrayList();
                ApplicationAccountBuilder abuilder = new ApplicationAccountBuilder();
                SessionInfoBuilder sbuilder = new SessionInfoBuilder();
                for(Object obj: list){
                    if(obj instanceof Map){
                        if("handshake".equals(resp.getCommand())){
                            SessionInfo sinfo = sbuilder.build(obj);
                            params.add(sinfo);
                        }else{
                            ApplicationAccount acct = abuilder.build(obj);
                            params.add(acct);
                        }
                    }else{
                        params.add(obj);
                    }
                }
                resp.setReturnValue(params);
            }else{
                resp.setReturnValue(list);
            }

            return resp;
        }

        return null;
    }
}
